import {
  Component,
  ChangeDetectionStrategy,
  OnInit,
  OnDestroy,
  NgZone,
  ChangeDetectorRef,
  ElementRef,
  Input,
} from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';
/**
 * 产品销售数据组件
 */
@Component({
  selector: 'product-saledata',
  templateUrl: './product-sale.component.html',
  styleUrls: ['./product-sale.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductSaleDataComponent implements OnInit, OnDestroy {
  _codeName = null;
  @Input()
  set codeName(val) {
    if (val) {
      this._codeName = val;
      this.attachData(this._codeName);
    }
  }

  loading = true;
  data = [];
  barData = [];
  sum = 0;
  time = null;
  start = null;
  end = null;

  constructor(
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  ngOnInit(): void {}

  ngOnDestroy(): void {
    // this.ref$.unsubscribe();
  }

  private attachData(codeName) {
    const { ngZone } = this;
    ngZone.run(() => {
      this.loading = true;
      this.cdr.detectChanges();
    });

    this.http.get(`/cf/report/prod/salesdata/${codeName}`).subscribe((res: any) => {
      ngZone.run(() => {
        if (res.data) {
          this.data = [];
          this.barData = [];
          this.time = res.data.time;
          this.start = res.data.start;
          this.end = res.data.end;
          const colors = ['#45a3fc', '#f0657d', '#fad352'];
          for (let i = 0; i < res.data.list.length; i++) {
            this.data.push({
              text: res.data.list[i].CHANNEL,
              count: res.data.list[i].NOWSC,
              count2: res.data.list[i].NOWCC,
              color: colors[i],
            });

            this.barData.push({
              company: '产品季',
              type: res.data.list[i].CHANNEL,
              value: res.data.list[i].NOWSC,
              value2: res.data.list[i].NOWCC,
            });
            this.barData.push({
              company: '近一年',
              type: res.data.list[i].CHANNEL,
              value: res.data.list[i].LASTSC,
              value2: res.data.list[i].LASTCC,
            });
          }
          this.sum = this.data.reduce((p, c) => (p += c.count), 0);
        }
        this.loading = false;
        this.cdr.detectChanges();
      });
    });
  }
}
